<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js数组之遍历</title>
</head>
<body>
  <ul>
    <li>可利用for,for..in,for..of,forEach对数组进行遍历</li>
    <li>可利用forEach对DOM元素直接遍历，而无需通过Array.from()或...转化为数组</li>
    <li>所有遍历方法针对引用类型数组，当成员改变数组跟着发生变化，对基础类型数组，当成员改变数组本身则不发生变化</li>
    <li>无法通过break跳出forEach循环，只能使用try..catch跳出</li>
    <li>无法通过continue跳出本次forEach循环，只能使用return false</li>
  </ul>
  <script>
    const blogs = [
      { url: 'https://github.com/miracle-git/vue', title: 'Vue学习' },
      { url: 'https://github.com/miracle-git/react', title: 'React学习' },
      { url: 'https://github.com/miracle-git/angular', title: 'Angular学习' }
    ]
    // for
    // for (let i = 0, len = blogs.length; i < len; i++) {
    //   blogs[i].title = `Miracle's ${blogs[i].title}`
    // }
    // for..in
    // for (const key in blogs) {
    //   blogs[key].title = `Miracle's ${blogs[key].title}`
    // }
    // for..of
    // for (const item of blogs) {
    //   item.title = `Miracle's ${item.title}`
    // }
    // forEach
    blogs.forEach(function (item) {
      item.title = `Miracle's ${item.title}`
    })
    console.table(blogs)
    // 遍历DOM
    const lis = document.querySelectorAll('li')
    lis.forEach(function (item) {
      console.log(item)
    })
    // 遍历基础类型
    const nums = [1, 2, 3, 4, 5]
    nums.forEach(function (item) {
      item++
    })
    console.log(nums)  // [1, 2, 3, 4, 5]
    // forEach..continue
    blogs.forEach(function (item) {
      if (item.title.includes('React')) return false
      item.title = `${item.title.replace(/Miracle\'s/, '').trim()}`
      console.log('forEach..continue', item)
    })
    console.table(blogs)
    // forEach..break
    try {
      blogs.forEach(function (item) {
        if (item.title.includes('React')) throw new Error('')
        item.title = `${item.title.replace(/Miracle\'s/, '').trim()}`
        console.log('forEach..break', item)
      })
    } catch (e) {
    }
    console.table(blogs)
  </script>
</body>
</html>